
<template>
  <div class="AddOrUpdate_main add_container column_three">
    <div class="main_main">
      <el-form ref="form" :model="formData" :rules="rules" :inline="true">
        <el-form-item label="出库单号" prop="formCode">
          <CodeRuleInput :band-value.sync="formData.formCode" table-name="device_spare_out" column-name="form_code" :is-edit="id" />
        </el-form-item>
        <el-form-item label="出库类型" prop="formTypeCode">
          <DictSelect :band-value.sync="formData.formTypeCode" dict-type="spare_parts_warehouse_out" />
        </el-form-item>
        <el-form-item label="绑定表单">
          <el-select v-model="formData.parentFormCode" clearable filterable>
            <el-option
              v-for="item in bindingForm"
              :key="item.code"
              :label="item.code"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="出库人员">
          <el-input v-model="formData.realName" placeholder="暂无" disabled />
          <!--          <el-select v-model="formData.outBy" filterable disabled>-->
          <!--            <el-option-->
          <!--              v-for="item in userList"-->
          <!--              :key="item.userId"-->
          <!--              :label="item.realName"-->
          <!--              :value="item.userId"-->
          <!--            />-->
          <!--          </el-select>-->
        </el-form-item>
        <el-form-item label="出库时间" class="time">
          <el-date-picker
            v-model="formData.outTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm"
            format="yyyy-MM-dd HH:mm"
            placeholder="请选择"
            :editable="false"
          />
        </el-form-item>
        <!-- <el-form-item label="附件" class="double">
          <FileManageFull
            :file-names="formData.fileName"
            :file-real-names="formData.fileRealName"
            :file-urls="formData.url"
            :row-index="1"
            @fileName="setFileName"
          />
        </el-form-item> -->
        <el-form-item label="备注" class="double">
          <el-input v-model="formData.remark" type="textarea" placeholder="请输入" maxlength="200" show-word-limit />
        </el-form-item>
      </el-form>
      <div class="formItem_header">
        <div class="formItem_header_operate">
          <a class="formItem_header_operate_item" @click="addSparePartsMaterials">
            <svg-icon icon-class="新增" />
            <div class="item_name">添加</div>
          </a>
          <a class="formItem_header_operate_item" @click="importData">
            <svg-icon icon-class="导入" />
            <div class="item_name">导入</div>
          </a>
          <a class="formItem_header_operate_item delete" @click="remove1">
            <svg-icon icon-class="删除" />
            <div class="item_name">删除</div>
          </a>
        </div>
      </div>
      <div ref="table_container2" class="table_container">
        <el-table
          ref="table"
          :data="tableData"
          :height="tableHeight"
          stripe
          border
          :header-cell-class-name="headerCellClassName"
          @selection-change="selectionChange1"
        >
          <el-table-column type="selection" align="center" width="100" />
          <el-table-column
            prop="spareCode"
            label="备件编码"
            :show-overflow-tooltip="true"
            min-width="120"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.spareCode }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="spareName"
            label="备件名称"
            :show-overflow-tooltip="true"
            min-width="100"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.spareName }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="spareModel"
            label="规格型号"
            :show-overflow-tooltip="true"
            min-width="200"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.spareModel }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="supplierName"
            label="备件供应商"
            min-width="100"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.supplierName }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="numberUnitLabel"
            label="备件单位"
            min-width="100"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.numberUnitLabel }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="deviceSpareWarehouseName"
            label="仓库"
            :show-overflow-tooltip="true"
            min-width="100"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.deviceSpareWarehouseName }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="batch"
            label="批号"
            min-width="100"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.batch }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="number"
            label="库存数量"
            :min-width="SETTINGS.settings_decimalDigits_length"
          />
          <el-table-column
            prop="outNumber"
            label="出库数量"
            fixed="right"
            :min-width="SETTINGS.settings_decimalDigits_length"
          >
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.outNumber"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <div class="main_bottom">
      <el-button type="cancel" @click.stop="cancel">取消</el-button>
      <el-button @click.stop="onSubmit">提交</el-button>
    </div>
  </div>
</template>

<script>
import { addOrUpdate, getInfo, getUserList, listAllRepairAndMaintainEnd, importMethod } from '@/api/equipmentManage/sparePart/outWarehouse'
import ImportData from '@/components/JLink/common/ImportData'
import addMaterials from './chooseSpareParts.vue'
import { list } from '@/api/equipmentManage/sparePart/warehouse'
import { mapGetters } from 'vuex'
import moment from 'moment'
export default {
  name: 'AddOrUpdate',
  props: {
    layerid: {},
    id: {},
    defaultValue: {}
  },
  data() {
    return {
      formData: {
        id: undefined,
        code: undefined,
        name: undefined,
        roleIdsArray: undefined,
        roleIds: undefined,
        status: '1',
        companyId: undefined,
        formTypeCode: '',
        formCode: '',
        outBy: '',
        outTime: '',
        fileName: '',
        fileRealName: '',
        url: '',
        remark: '',
        parentFormCode: ''
      },
      pageId: '备件出库',
      pageData: {
        pageNum: 1,
        pageSize: 20,
        orderByColumn: 'updateTime',
        isAsc: 'desc'
      },
      typeList: [
        { value: 1, label: '采购入库' },
        { value: 2, label: '外协入库' },
        { value: 3, label: '成品入库' }
      ],
      selectData: [],
      tableData: [],
      selectionsAll1: [],
      tableHeight: '330',
      num: 1,
      roleOptions: [],
      rules: {
        formCode: [
          { required: true, message: '表单编码不能为空', trigger: 'blur' }
        ],
        formTypeCode: [
          { required: true, message: '表单类型不能为空', trigger: 'change' }
        ]
      },
      objectData: [],
      userList: [],
      bindingForm: []
    }
  },
  computed: {
    ...mapGetters([
      'userId', 'userName'
    ])
  },
  created() {
    if (!this.id) { // 没有id就是新增
      Object.keys(this.defaultValue).forEach(key => { // 给右边数据赋值
        this.formData[key] = this.defaultValue[key]
      })
    } else { // 有id就是编辑
      this.getInfo()
    }
  },
  mounted() {
    this.getList()
    this.laodUserList()
    this.loadlistAllRepairAndMaintainEnd()
    this.formData.outBy = this.userId
    this.formData.realName = this.userName
    this.formData.outTime = moment(new Date()).format('YYYY-MM-DD HH:mm')
  },
  methods: {
    setFileName(...data) {
      this.$set(this.formData, 'fileName', data[0])
      this.$set(this.formData, 'fileRealName', data[1])
      this.$set(this.formData, 'url', data[2])
    },
    headerCellClassName(data) {
      if (['outNumber'].indexOf(data.column.property) != -1) {
        return 'column_bt'
      }
    },
    selectionChange1(rows) {
      this.selectionsAll1 = rows
    },
    importData() { // 导入
      this.$layer.iframe({// 弹框
        content: {
          content: ImportData, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {}// props
        },
        area: ['440px', '250px'],
        title: '导入数据', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    importMethod(files) { // 导入接口
      importMethod(files).then(res => {
        if (res.data) {
          this.tableData = []
          res.data.forEach(item => {
            item.id = item.batchId
            if (Number(item.number) > Number(item.batchInventoryNumber)) {
              this.$message.warning('导入的数据中存在出库数量大于库存数量的数据,请修改后重新导入')
              return false
            } else {
              this.addRow(item)
            }
          })
        }
      })
    },
    addRow(row) {
      const row2 = [
        {
          id: row.id || '',
          spareCode: row.spareCode || '',
          spareName: row.spareName || '',
          spareModel: row.spareModel || '',
          batch: row.batch || '',
          supplierName: row.supplierName || '',
          numberUnitLabel: row.numberUnitLabel || '',
          number: row.batchInventoryNumber || '',
          outNumber: row.number || '',
          deviceSpareWarehouseName: row.deviceSpareWarehouseName || '',
          deviceSpareStandingBookId: row.deviceSpareStandingBookId || '',
          deviceSpareWarehouseId: row.deviceSpareWarehouseId || ''
        }
      ]
      this.tableData.push(...row2)
    },
    laodUserList() {
      getUserList({
        companyId: this.$store.state.companyId
      }).then(res => {
        console.log(res)
        this.userList = res.data
      })
    },
    loadlistAllRepairAndMaintainEnd() {
      listAllRepairAndMaintainEnd().then(res => {
        this.bindingForm = res.data
      })
    },
    getList() {
      list(this.pageData).then(res => {
        this.selectData = res.data
      })
    },
    getInfo() {
      getInfo(this.id).then(res => {
        this.formData.companyId = res.company.companyId
      })
    },
    onSubmit() {
      if (this.tableData.length == 0) {
        this.$message.warning('请添加备件信息')
        return false
      } else {
        this.$refs['form'].validate(valid => {
          if (valid) {
            if (this.tableData.filter(item => item.outNumber && Number(item.outNumber) > Number(item.number)).length > 0) {
              this.$message.warning('出库数量不能大于库存数量')
              return
            } else if (this.tableData.filter(item => !item.outNumber).length > 0) {
              this.$message.warning('出库数量不能为空')
              return
            } else if (this.tableData.filter(item => item.outNumber && !this.SETTINGS.reg_no_zero.test(item.outNumber)).length > 0) {
              this.$message.warning('出库数量未正确填写')
              return
            } else if (this.tableData.some(item => !item.outNumber || item.outNumber < 0)) {
              this.$message.warning('请正确填写出库数量')
              return
            } else {
              this.objectData = []
              this.tableData.forEach(item => {
                const obj = {
                  ...item,
                  ...this.formData
                }
                this.objectData.push(obj)
              })
              addOrUpdate(this.objectData).then(res => {
                this.$message({
                  message: res.msg,
                  type: 'success'
                })
                this.$layer.close(this.layerid) // 关闭弹框
                this.$parent.refresh() // 调用父组件的刷新方法
              })
            }
          }
        })
      }
    },
    cancel() {
      this.$layer.close(this.layerid)// 关闭弹框
    },
    removeRow(index) {
      this.tableData.splice(index, 1)
    },
    remove1() {
      this.selectionsAll1.forEach(item => {
        this.tableData.splice(this.tableData.indexOf(item), 1)
      })
    },
    // 选择备件信息
    addSparePartsMaterials() {
      this.$layer.iframe({// 弹框
        content: {
          content: addMaterials, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            selectedRow: this.tableData
          }// props
        },
        area: ['1320px', '700px'],
        title: '选择备件信息', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    addMaterial(data) {
      this.tableData = data
    }
  }
}
</script>

<style lang="less" scoped>
/deep/ .el-table__body-wrapper {
  padding-bottom:6px;
}

.formItem_header{
  justify-content: flex-end !important;
  align-items: flex-start !important;
  height: 40px !important;
}
</style>
